package com.d3works.studio.web;

import com.d3works.inject.Beans;
import com.d3works.meta.db.MetaJsonModel;
import com.d3works.rpc.ActionRequest;
import com.d3works.rpc.ActionResponse;
import com.d3works.studio.db.MenuBuilder;
import com.d3works.studio.db.repo.MenuBuilderRepo;
import com.d3works.studio.db.repo.MenuBuilderRepository;
import com.d3works.studio.db.repo.MetaJsonModelRepo;
import com.google.inject.persist.Transactional;

public class MetaJsonModelController {

  @Transactional
  public void removeMenuBuilder(ActionRequest request, ActionResponse response) {

    MetaJsonModel metaJsonModel = request.getContext().asType(MetaJsonModel.class);
    if (metaJsonModel.getMenuBuilder() != null
        && metaJsonModel.getMenuBuilder().getId() != null
        && metaJsonModel.getMenuBuilder().getMetaMenu() != null) {
      MenuBuilder menuBuilder =
          Beans.get(MenuBuilderRepository.class).find(metaJsonModel.getMenuBuilder().getId());

      metaJsonModel = Beans.get(MetaJsonModelRepo.class).find(metaJsonModel.getId());
      metaJsonModel.setMenuBuilder(null);
      Beans.get(MetaJsonModelRepo.class).save(metaJsonModel);
      Beans.get(MenuBuilderRepo.class).remove(menuBuilder);
      response.setReload(true);
    }
  }
}
